﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using YT.DB;
using YT.Controls;
using YT.Commons;
using YT.Controls.OutlookStyleNavigateBar;
using YT.Modules;
using YT.XH.SMS;
using System.Runtime.InteropServices;



namespace YT_XHProject
{
    public partial class frmMainMenu : Form
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数
        public static extern bool RegisterHotKey(
         IntPtr hWnd, // handle to window 
         int id, // hot key identifier 
         uint fsModifiers, // key-modifier options 
         Keys vk // virtual-key code 
        );
        [System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数
        public static extern bool UnregisterHotKey(
         IntPtr hWnd, // handle to window 
         int id // hot key identifier 
        );

        public enum KeyModifiers //组合键枚举
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }

        private bool mblnExit = false;

        NavigateBarButton nvbWP;
        NavigateBarButton nvbGL;
        NavigateBarButton nvbAP;
        NavigateBarButton nvbAR;
        NavigateBarButton nvbOE;
        NavigateBarButton nvbIM;
        public frmMainMenu()
        {
            InitializeComponent();
        }

        private void ProcessHotkey(Message m) //按下设定的键时调用该函数
        {
            IntPtr id = m.WParam; //IntPtr用于表示指针或句柄的平台特定类型
            //MessageBox.Show(id.ToString());
            string sid = id.ToString();
            switch (sid)
            {
                case "100":
                    //MessageBox.Show("调用A函数");
                    ShowHotKeyForm(sid);
                    break;
                case "200":
                    ShowHotKeyForm(sid);
                    break;
            }
        }

        private void ShowHotKeyForm(string strSID)
        {
            if (SysVar.CurrentMenuInfo.strMenuId == "" || SysVar.CurrentMenuInfo.strMenuId == null) return;
            MenuInfo iminfo = new MenuInfo();
            if (strSID == "100") //病史调查
            {
                if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "100")
                    iminfo = DataFunctions.GetMenuInfo("100300100000");
                else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "200")
                    iminfo = DataFunctions.GetMenuInfo("200300100000");
                else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "300")
                    iminfo = DataFunctions.GetMenuInfo("300300100000");
                else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "400")
                    iminfo = DataFunctions.GetMenuInfo("400500210000");
                else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "500")
                    iminfo = DataFunctions.GetMenuInfo("500500210000");
                else
                    return;

            }
            else if (strSID == "200")  //治疗前检查
            {
                if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "100")
                    iminfo = DataFunctions.GetMenuInfo("100300120000");
                else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "200")
                    iminfo = DataFunctions.GetMenuInfo("200300120000");
                else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "300")
                    iminfo = DataFunctions.GetMenuInfo("300300120000");
                else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "500")
                    iminfo = DataFunctions.GetMenuInfo("500300120000");
                else
                    return;
            }
            TreeMenu trvMnu = new TreeMenu();
            trvMnu.ShowForm(iminfo);
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    ProcessHotkey(m);//按下热键时调用ProcessHotkey()函数
                    break;
            }
            base.WndProc(ref m);

        }

        private void initNagivate()
        {
            DBAccess dbcon = new DBAccess(false, false);
            int iCollapsedScreenWidth = 300;
            outlookNavigateBar.SaveAndRestoreSettings = false;
            outlookNavigateBar.Dock = DockStyle.Left;
            outlookNavigateBar.IsShowCollapsibleScreen = true;
            outlookNavigateBar.CollapsedScreenWidth = iCollapsedScreenWidth; // For all buttons
            outlookNavigateBar.CollapsibleWidth = 40;

            outlookNavigateBar.Width = iCollapsedScreenWidth;

            outlookNavigateBar.NavigateBarDisplayedButtonCount = 12; // Max display 5 button in panel
            TreeMenu oTreeMenu = null;

            nvbWP = new NavigateBarButton();
            oTreeMenu = new TreeMenu(dbcon, YT.Commons.SystemModules.MeniereDisease, this);
            //oTreeMenu.SetWindowFocus += new TreeMenu.SetWindowFocusEventHandler(OnSetWindowFocus);
            nvbWP.RelatedControl = oTreeMenu;
            nvbWP.Caption = "梅尼埃病";
            nvbWP.CaptionDescription = "梅尼埃病";
            nvbWP.IsShowCaptionDescription = false;
            nvbWP.Image = imageList1.Images[1];
            nvbWP.Enabled = true;
            nvbWP.Key = "梅尼埃病病例";
            nvbWP.IsShowCaptionImage = false;
            nvbWP.CollapsedScreenWidth = iCollapsedScreenWidth;

            oTreeMenu = null;
            nvbGL = new NavigateBarButton();
            oTreeMenu = new TreeMenu(dbcon, YT.Commons.SystemModules.SUDDENDEAFNESS, this);
            //oTreeMenu.SetWindowFocus += new TreeMenu.SetWindowFocusEventHandler(OnSetWindowFocus);
            nvbGL.RelatedControl = oTreeMenu;
            nvbGL.Caption = "突发性耳聋";
            nvbGL.CaptionDescription = "突发性耳聋";
            nvbGL.IsShowCaptionDescription = false;
            nvbGL.Image = imageList1.Images[0];
            nvbGL.Enabled = true;
            nvbGL.Key = "突发性耳聋";
            nvbGL.IsShowCaptionImage = false;
            nvbGL.CollapsedScreenWidth = iCollapsedScreenWidth;


            oTreeMenu = null;
            nvbAP = new NavigateBarButton();
            oTreeMenu = new TreeMenu(dbcon, YT.Commons.SystemModules.Dizziness, this);
            //oTreeMenu.SetWindowFocus += new TreeMenu.SetWindowFocusEventHandler(OnSetWindowFocus);
            nvbAP.RelatedControl = oTreeMenu;
            nvbAP.Caption = "良性阵发性位置性眩晕";
            nvbAP.CaptionDescription = "良性阵发性位置性眩晕";
            nvbAP.IsShowCaptionDescription = false;
            nvbAP.Image = imageList1.Images[2];
            nvbAP.Enabled = true;
            nvbAP.Key = "良性阵发性位置性眩晕";
            nvbAP.IsShowCaptionImage = false;
            nvbAP.CollapsedScreenWidth = iCollapsedScreenWidth;



            oTreeMenu = null;
            nvbAR = new NavigateBarButton();
            oTreeMenu = new TreeMenu(dbcon, YT.Commons.SystemModules.NOSE, this);
            //oTreeMenu.SetWindowFocus += new TreeMenu.SetWindowFocusEventHandler(OnSetWindowFocus);
            nvbAR.RelatedControl = oTreeMenu;
            nvbAR.Caption = "变应性鼻炎";
            nvbAR.CaptionDescription = "变应性鼻炎";
            nvbAR.IsShowCaptionDescription = false;
            nvbAR.Image = imageList1.Images[2];
            nvbAR.Enabled = true;
            nvbAR.Key = "变应性鼻炎";
            nvbAR.IsShowCaptionImage = false;
            nvbAR.CollapsedScreenWidth = iCollapsedScreenWidth;

            oTreeMenu = null;
            nvbOE = new NavigateBarButton();
            oTreeMenu = new TreeMenu(dbcon, YT.Commons.SystemModules.Others, this);
            //oTreeMenu.SetWindowFocus += new TreeMenu.SetWindowFocusEventHandler(OnSetWindowFocus);
            nvbOE.RelatedControl = oTreeMenu;
            nvbOE.Caption = "其它眩晕疾病";
            nvbOE.CaptionDescription = "其它眩晕疾病";
            nvbOE.IsShowCaptionDescription = false;
            nvbOE.Image = imageList1.Images[2];
            nvbOE.Enabled = true;
            nvbOE.Key = "其它类型眩晕";
            nvbOE.IsShowCaptionImage = false;
            nvbOE.CollapsedScreenWidth = iCollapsedScreenWidth;

            oTreeMenu = null;
            nvbIM = new NavigateBarButton();
            oTreeMenu = new TreeMenu(dbcon, YT.Commons.SystemModules.IgE, this);
            //oTreeMenu.SetWindowFocus += new TreeMenu.SetWindowFocusEventHandler(OnSetWindowFocus);
            nvbIM.RelatedControl = oTreeMenu;
            nvbIM.Caption = "屋尘螨IgG4分析系统";
            nvbIM.CaptionDescription = "屋尘螨IgG4分析系统";
            nvbIM.IsShowCaptionDescription = false;
            nvbIM.Image = imageList1.Images[2];
            nvbIM.Enabled = true;
            nvbIM.Key = "屋尘螨IgG4分析系统";
            nvbIM.IsShowCaptionImage = false;
            nvbIM.CollapsedScreenWidth = iCollapsedScreenWidth;

            string strSQL = string.Empty;
            string strGroupNo = DataFunctions.GetFieldValue("mUser", "GroupNo", "UserName='" + SysVar.UserName + "'");
            if (strGroupNo == "") strGroupNo = "01";
            if (strGroupNo == "01")
                strSQL = "select distinct Permit01,MenuType from mMenu where Permit01='1' ";
            else if (strGroupNo == "02")
                strSQL = "select distinct Permit02,MenuType from mMenu where Permit02='1'";
            else if (strGroupNo == "03")
                strSQL = "select distinct Permit03,MenuType from mMenu where Permit03='1'";
            else if (strGroupNo == "04")
                strSQL = "select distinct Permit04,MenuType from mMenu where Permit04='1'";
            else if (strGroupNo == "05")
                strSQL = "select distinct Permit05,MenuType from mMenu where Permit05='1'";
            else if (strGroupNo == "06")
                strSQL = "select distinct Permit05,MenuType from mMenu where Permit06='1'";
            DataTable dtPermit = dbcon.GetDataTable(strSQL);
            foreach (DataRow drPermit in dtPermit.Rows)
            {
                if (CvtFunc.ToString(drPermit["MenuType"]) == "100") outlookNavigateBar.NavigateBarButtons.Add(nvbWP);
                if (CvtFunc.ToString(drPermit["MenuType"]) == "200") outlookNavigateBar.NavigateBarButtons.Add(nvbGL);
                if (CvtFunc.ToString(drPermit["MenuType"]) == "300") outlookNavigateBar.NavigateBarButtons.Add(nvbAP);
                if (CvtFunc.ToString(drPermit["MenuType"]) == "400") outlookNavigateBar.NavigateBarButtons.Add(nvbAR);
                if (CvtFunc.ToString(drPermit["MenuType"]) == "500") outlookNavigateBar.NavigateBarButtons.Add(nvbOE);
                if (CvtFunc.ToString(drPermit["MenuType"]) == "600") outlookNavigateBar.NavigateBarButtons.Add(nvbIM);
            }

            outlookNavigateBar.NavigateBarButtonHeight = 40;
            outlookNavigateBar.Show();
            outlookNavigateBar.NavigateBarDisplayedButtonCount = 6;
        }

        private void FillDesc()
        {
            toolStripStatusCaseName.Text = DataFunctions.GetFieldValue("mHospital", "HospitalName", " HospitalID='" + SysVar.HospitalID + "'");
        }


        private void frmMainMenu_Load(object sender, EventArgs e)
        {
            initNagivate();
            FillDesc();
            timer1.Start();
            timer2.Start();
            this.Refresh();
            bgRecvAndSendMsg.RunWorkerAsync();
            if (SysVar.IsNose)
            {
                btnAgree.Visible = false;
                this.Text = "变应性鼻炎规范化治疗方案研究软件平台";
            }

            RegisterHotKey(Handle, 100, 0, Keys.F1); //定义热键为Alt+Tab，这里实现了屏幕系统Alt+Tab键
            RegisterHotKey(Handle, 200, 0, Keys.F2); //注册2个热键,根据id值100,200来判断需要执行哪个函数

        }



        //private void button1_Click_1(object sender, EventArgs e)
        //{
        //    frmLogin frmnew = new frmLogin();
        //    frmnew.MdiParent = this;
        //    frmnew.StartPosition = FormStartPosition.CenterScreen;
        //    frmnew.Show();
        //}

        private void FillMenu()
        {






        }

        private void frmMainMenu_FormClosed(object sender, FormClosedEventArgs e)
        {

            UnregisterHotKey(Handle, 100);//卸载第1个快捷键
            UnregisterHotKey(Handle, 200); //缷载第2个快捷键

            System.Windows.Forms.Application.Exit();
            System.Windows.Forms.Application.DoEvents();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void mtSplitter1_SplitterMoved(object sender, SplitterEventArgs e)
        {
            this.Refresh();
        }

        private void outlookNavigateBar_StyleChanged(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void outlookNavigateBar_OnNavigateBarCollapseModeChanged(bool tIsCollaped)
        {
            this.Refresh();
        }

        private void outlookNavigateBar_OnNavigateBarButtonSelected(NavigateBarButton tNavigateBarButton)
        {
            int j = SysVar.mfrmMdiPar.MdiChildren.Length;

            if (SysVar.mfrmMdiPar.MdiChildren.Length > 0)
                for (int i = 0; i <= j - 1; i++)
                {
                    SysVar.mfrmMdiPar.MdiChildren[0].Close();
                }

            SysVar.marrFormList.Clear();
        }

        private void btnAgree_Click(object sender, EventArgs e)
        {
            string strPath = Application.StartupPath;
            string strFileName = string.Empty;
            if (SysVar.IsNose)
                strFileName = strPath + "\\知情同意书_变应性鼻炎.doc";
            else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "100" || SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "500")
                strFileName = strPath + "\\知情同意书_梅尼埃病.doc";
            else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "200")
                strFileName = strPath + "\\知情同意书.doc";
            else if (SysVar.CurrentMenuInfo.strMenuId.Substring(0, 3) == "300")
                strFileName = strPath + "\\知情同意书_良性阵发性位置性眩晕.doc";
            else
                return;

            System.Diagnostics.Process.Start(strFileName);
        }

        private void ChangeOpacity()
        {
            if (mblnExit == false)
            {
                if (this.Opacity >= 1)
                    timer1.Stop();
                this.Opacity += 0.04;
            }
            else
            {
                if (this.Opacity <= 0.01)
                {
                    timer1.Stop();
                }
                this.Opacity -= 0.04;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ChangeOpacity();
        }

        private void frmMainMenu_Resize(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAbout frmabout = new frmAbout();
            frmabout.ShowDialog();
        }

        private void frmMainMenu_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("您确定要退出系统吗？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (!SysVar.IsIgE)
                {
                    frmGifImage frmGif = new frmGifImage();
                    frmGif.ShowDialog();
                    timer1.Interval = 6;
                    mblnExit = true;
                    //timer1.Start();
                    //this.Close();
                }
            }
            else
                e.Cancel = true;
        }

        private void bgRecvAndSendMsg_DoWork(object sender, DoWorkEventArgs e)
        {
            if (DateTime.Now.Hour > 10 && DateTime.Now.Hour < 20)
            {
                SendReturnVisitMsg();
                SendMsgToHardWare();
            }
            RecvMsgFromHardWare();
        }

        private void SendMsgToHardWare()
        {
            SMS smsSys = new SMS();
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = string.Empty;
            string strMsg = string.Empty;
            string strMobNo = string.Empty;
            string strSickName = string.Empty;
            strSQL = "select * from SmsOutbox where SendSuccess=0 and senddate<= getdate()";
            DataTable dtSend = dbcon.GetDataTable(strSQL);
            foreach (DataRow drSend in dtSend.Rows)
            {
                strMsg = CvtFunc.ToString(drSend["Message"]);
                strMobNo = CvtFunc.ToString(drSend["MobilePhone"]);
                strSickName = CvtFunc.ToString(drSend["SickName"]);
                System.Threading.Thread.Sleep(500);
                smsSys.SendMsg(strMsg, strMobNo, strSickName);
                strSQL = "update  SmsOutbox set SendSuccess=1 where recid='" + CvtFunc.ToString(drSend["RecID"]) + "'";
                dbcon.ExecuteSql(strSQL);
            }
            dbcon.CloseCon();
            dbcon = null;
        }


        private void RecvMsgFromHardWare()
        {
            DBAccess dbcon = new DBAccess(false, false);
            DataFunctions.InsertIntoMsgTable(dbcon);
            dbcon.CloseCon();
            dbcon = null;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            bgRecvAndSendMsg.RunWorkerAsync();
        }

        private void SendReturnVisitMsg()
        {
            string strMsg = DataFunctions.GetFieldValue("mSmsMessage", "SmsMessage", "Type='S'");
            int intAddDays = 3;  //用于提前发送的天数
            string strSQL = @" select  A.TreatDate,C.SickName,C.HospitalName, C.MobilePhone,                                               
                                   A.TreatDate as LastTreatDate,C.SickRecID, C.SickName,A.NextTreatDate as SDate   " +
                                "  from NoseDrTreatHistoryDtl as A inner join ( " +
                                "  select max(treatdate) as LastDate ,SickRecID from NoseDrTreatHistoryDtl group by sickrecid " +
                                "  ) B " +
                                "  on a.sickrecid=b.sickrecid and A.TreatDate=B.LastDate " +
                                "  inner join mSickPerson C on A.SickRecID=C.SickRecID " +
                                "  where dateadd(day,{0}, NextTreatDate)<= getdate()";
            strSQL = string.Format(strSQL, intAddDays);
            DBAccess dbcon = new DBAccess(false, false);
            DataTable dtMsg = dbcon.GetDataTable(strSQL);
            foreach (DataRow drRow in dtMsg.Rows)
            {
                strSQL = @" select RecID,SickRecID,NextTreatMsg from NoseDrTreatHistoryDtl
                           where sickrecid='{0}' and TreatDate='{1}' and NextTreatMsg=1 ";
                strSQL = string.Format(strSQL, drRow["SickRecID"], drRow["LastTreatDate"]);
                DataRow drCheck = dbcon.GetDataFirstRow(strSQL);
                if (drCheck == null) // 没有发送过短信
                {
                    System.Threading.Thread.Sleep(500);
                    strSQL = @" Insert into SmsOutBox ( SickName,MobilePhone,Message,SendDate,MsgType,SickRecID)
                            VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')";
                    strSQL = string.Format(strSQL, drRow["SickName"], drRow["MobilePhone"], strMsg, DateTime.Now, "S", drRow["SickRecID"]);
                    dbcon.ExecuteSql(strSQL);

                    strSQL = "select RecID,SickRecID from NoseDrTreatHistoryDtl where sickrecid='" + drRow["SickRecID"] + "' and TreatDate='" + CvtFunc.ToString(drRow["LastTreatDate"]) + "'";
                    DataRow drDtl = dbcon.GetDataFirstRow(strSQL);
                    if (drRow != null)
                    {
                        strSQL = "update NoseDrTreatHistoryDtl set NextTreatMsg=1 where recid='" + drDtl["RecID"] + "'";
                        dbcon.ExecuteSql(strSQL);
                    }
                }
            }
        }
    }
}
